package com.wx.commons.config.exception;

import com.wx.commons.model.CommonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandle {
    //捕获@Valid校验不通过的异常
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public CommonResult<String> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        log.error(e.getMessage(), e);
        BindingResult ex = e.getBindingResult();
        List<ObjectError> allErrors = ex.getAllErrors();
        ObjectError error = allErrors.get(0);
        String defaultMessage = error.getDefaultMessage();
        return CommonResult.failed(defaultMessage);
    }

    @ExceptionHandler(FileSaveException.class)
    public CommonResult<String> handleFileSaveException(FileSaveException e) {
        log.error(e.getMessage(), e);
        return CommonResult.failed(e.getMessage());
    }

    @ExceptionHandler(Exception.class)
    public CommonResult<String> handleException(Exception e) {
        return CommonResult.failed(e.getMessage());
    }

}



